using System;
using System.Collections;
using UnityEngine;

namespace EventBehaviorTree
{
    [Serializable]
    public class Asynchronous : EventNode
    {
        private AsyncWorker _asyncWorker;
        private Action[] _actions;
        public Asynchronous(params Action[] actions) { _actions = actions; }

        public override void SetCoroutineStarter(MonoBehaviour coroutineStarter)
        {
            _asyncWorker = new AsyncWorker(coroutineStarter);
        }

        private IEnumerator Worker()
        {
            SuperiorNodeEvent(NodeMsg.Succeed);
            while (true)
            {
                yield return null;
                foreach (Action action in _actions) action();//action per frame
            }
        }

        public override void NodeEvent(NodeMsg nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMsg.Start:
                    if (!_isWorking)
                    {
                        _isWorking = true;
                        _asyncWorker.ResetWorker(Worker());
                        _asyncWorker.Start();
                    }
                    break;
                case NodeMsg.CMD_Stop:
                    if (_isWorking)
                    {
                        _asyncWorker.ResetWorker(Worker());
                        _isWorking = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }
}
